package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.xiaoymin.knife4j.core.util.CollectionUtils;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.HttpClientUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.*;
import com.sky.websocket.WebSocketServer;
import io.swagger.models.auth.In;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    OrderDetailMapper orderDetailMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private UserMapper userMapper;

    @Value("${sky.shop.address}")
    private String shopAddress;

    @Value("${sky.baidu.ak}")
    private String ak;

    @Autowired
    private WebSocketServer webSocketServer;


    /**
     * 检查客户的收货地址是否超出配送范围
     * https://api.map.baidu.com/geocoding/v3/?address=北京市海淀区上地十街10号&output=json&ak=您的ak&callback=showLocation
     * @param address
     */
    private void checkOutOfRange(String address) {
        Map map = new HashMap();
        map.put("address",shopAddress);
        map.put("output","json");
        map.put("ak",ak);
//        map.put("callback","showLocation");

        // 1.获取商家店铺的经纬度坐标
        String shopCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        JSONObject jsonObject = JSON.parseObject(shopCoordinate);
        if(!jsonObject.getString("status").equals("0")){// 本次API访问状态，如果成功返回0，如果失败返回其他数字
            throw new OrderBusinessException("店铺地址解析失败");
        }

        //数据解析
        JSONObject location = jsonObject.getJSONObject("result").getJSONObject("location");
        String lat = location.getString("lat");
        String lng = location.getString("lng");
        //店铺经纬度坐标
        String shopLngLat = lat + "," + lng;
        //---------------------------------------------------------------------------------------------------
        map.put("address",address);
        // 2.获取用户收货地址的经纬度坐标
        String userCoordinate = HttpClientUtil.doGet("https://api.map.baidu.com/geocoding/v3", map);

        jsonObject = JSON.parseObject(userCoordinate);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("收货地址解析失败");
        }

        //数据解析
        location = jsonObject.getJSONObject("result").getJSONObject("location");
        lat = location.getString("lat");
        lng = location.getString("lng");
        //用户收货地址经纬度坐标
        String userLngLat = lat + "," + lng;

        // https://api.map.baidu.com/directionlite/v1/driving?origin=40.01116,116.339303&destination=39.936404,116.452562&ak=您的AK
        // 3.通过驾车路线规划服务来计算两个经纬度的距离
        map.put("origin",shopLngLat);// 店铺经纬度坐标作为起点
        map.put("destination",userLngLat);// 用户收货地址经纬度坐标作为终点
        map.put("steps_info","0");

        //路线规划
        String json = HttpClientUtil.doGet("https://api.map.baidu.com/directionlite/v1/driving", map);

        jsonObject = JSON.parseObject(json);
        if(!jsonObject.getString("status").equals("0")){
            throw new OrderBusinessException("配送路线规划失败");
        }

        //数据解析
        JSONObject result = jsonObject.getJSONObject("result");
        JSONArray jsonArray = (JSONArray) result.get("routes");
        Integer distance = (Integer) ((JSONObject) jsonArray.get(0)).get("distance");

        if(distance > 5000){
            //配送距离超过5000米
            throw new OrderBusinessException("超出配送范围");

        }
    }

    /**
     * 支付成功，修改订单状态
     *  模拟支付，提醒代码改在Payment()
     * webSocketServer 【来单提醒】
     * @param outTradeNo 订单号
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//
//        // 根据订单号查询当前用户的订单
//        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);
//
//        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
//        Orders orders = Orders.builder()
//                .id(ordersDB.getId())
//                .status(Orders.TO_BE_CONFIRMED)
//                .payStatus(Orders.PAID)
//                .checkoutTime(LocalDateTime.now())
//                .build();
//
//        orderMapper.update(orders);
//        //////////////////////////////////////////////
//        Map map = new HashMap();
//        map.put("type", 1);//消息类型，1表示来单提醒
//        map.put("orderId", orders.getId());// 订单id
//        map.put("content", "订单号：" + outTradeNo);// 订单号
//
//        //通过WebSocket实现来单提醒，向客户端浏览器推送消息
//        webSocketServer.sendToAllClient(JSON.toJSONString(map));
        ///////////////////////////////////////////////////
    }



    /**
     * 提交订单
     * @param ordersSubmitDTO
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public OrderSubmitVO submitOrder(OrdersSubmitDTO ordersSubmitDTO) {
        // 【1】 验证提交订单是否合法【购物车有数据，地址不为空】
        // 获取查询对象shoppingCart
        Long userId = BaseContext.getCurrentId();// 获取当前用户id
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);

        List<ShoppingCart> shoppingCartList = shoppingCartMapper.selectList(shoppingCart);
        if(shoppingCartList.isEmpty()||shoppingCartList.size()==0){
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);// 购物车数据为空
        }

        // 验证地址是否为空
        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if(addressBook==null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);// 用户地址为空
        }
        // 校验地址是否合理，超过5km不可送
        checkOutOfRange(addressBook.getCityName()+addressBook.getDistrictName()+addressBook.getDetail());


        // 【2】保存订单信息 insert into orders
        //构造订单数据
        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,order);
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setUserId(userId);
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setPayStatus(Orders.UN_PAID);
        order.setOrderTime(LocalDateTime.now());


        orderMapper.insertOrders(order);// 返回order的id，下面order_detail要使用
        // 【3】保存n条订单详情 insert into order_detail
        ArrayList<OrderDetail> list = new ArrayList<>();// 用于批量插入

        for (ShoppingCart cart : shoppingCartList) {
            // 每一个ShoppingCart就有一个order_detail
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(order.getId());// 设置order_id
            list.add(orderDetail);
        }

        orderDetailMapper.insertBatch(list);

        // 【完成下单之后】，清空购物车中的数据------------------>付款界面
        shoppingCartMapper.deleteAll(userId);

        // 封装OrderSubmitVO返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(order.getId())// 订单id
                .orderNumber(order.getNumber())// 订单号
                .orderAmount(order.getAmount())// 订单金额
                .orderTime(order.getOrderTime())// 订单时间
                .build();

        return orderSubmitVO;
    }


    /**
     * 订单完成
     * @param id
     */
    public void completeOrder(Long id) {
        // 把派送中的订单修改为“已完成”
        Orders order = orderMapper.getById(id);
        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if(order.getStatus() != Orders.DELIVERY_IN_PROGRESS){// 订单状态校验，只能是“待派送”状态
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        order.setStatus(Orders.COMPLETED); // 已完成
        order.setDeliveryTime(LocalDateTime.now());// 完成时间
        // 3.修改订单详情状态
        orderMapper.update(order);
    }

    /**
     * 商家派送订单
     * @param id
     */
    public void deliveryOrder(Long id) {
        //- 派送订单其实就是将订单状态修改为“派送中”
        //- 只有状态为“待派送”的订单可以执行派送订单操作
        // 1.根据id查询订单
        Orders order = orderMapper.getById(id);

        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        if(order.getStatus() != Orders.CONFIRMED){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 2.修改订单状态
        order.setStatus(Orders.DELIVERY_IN_PROGRESS); // 派送中
        order.setDeliveryStatus(1); // 派送状态deliveryStatus 1表示派送中
        // 3.修改订单详情状态
        orderMapper.update(order);
    }

    /**
     * 商家取消订单
     * @param ordersCancelDTO
     */
    public void adminCancel(OrdersCancelDTO ordersCancelDTO) {
        // 1.根据id查询订单
        Orders order = orderMapper.getById(ordersCancelDTO.getId());

        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 对于已结单的，商家可以取消
        if(order.getStatus() != Orders.CONFIRMED){//
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 2.修改订单状态
        order.setStatus(Orders.CANCELLED);// 订单状态修改为“已取消”
        order.setCancelReason("取消原因11"); //取消原因
        order.setCancelTime(LocalDateTime.now()); // 取消时间
        // 商家取消订单时，如果用户已经完成了支付，需要为用户退款
        if(order.getPayStatus() == Orders.PAID){
            // 调用微信支付退款接口，完成用户退款
            order.setPayStatus(Orders.REFUND);// 已退款
        }
        /*
         if (payStatus == 1) {
            //用户已支付，需要退款
            String refund = weChatPayUtil.refund(
                    ordersDB.getNumber(),
                    ordersDB.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            log.info("申请退款：{}", refund);
        }
         */

        // 3.修改订单详情状态
        orderMapper.update(order);
    }

    /**
     * 商家拒单
     * @param ordersRejectionDTO 订单id
     */
    public void rejectionOrder(OrdersRejectionDTO ordersRejectionDTO) {
        // 1.根据id查询订单
        Orders order = orderMapper.getById(ordersRejectionDTO.getId());

        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 订单只有存在且状态为2（待接单）才可以拒单
        if(order==null||order.getStatus() != Orders.TO_BE_CONFIRMED){
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        // 2.修改订单状态
        order.setStatus(Orders.CANCELLED);// 4已取消
        order.setRejectionReason("商家拒单");// 拒单原因
        order.setCancelTime(LocalDateTime.now());
        if(order.getPayStatus() == Orders.PAID){
            // 调用微信支付退款接口，完成用户退款【省略】
            order.setPayStatus(Orders.REFUND);// 已退款
        }
        /*
            //支付状态
        Integer payStatus = ordersDB.getPayStatus();
        if (payStatus == Orders.PAID) {
            //用户已支付，需要退款
            String refund = weChatPayUtil.refund(
                    ordersDB.getNumber(),
                    ordersDB.getNumber(),
                    new BigDecimal(0.01),
                    new BigDecimal(0.01));
            log.info("申请退款：{}", refund);
        }
         */

        // 3.修改订单详情状态
        orderMapper.update(order);

    }

    /**
     * 商家确认订单
     * @param ordersConfirmDTO 订单id
     */
    public void confirmOrder(OrdersConfirmDTO ordersConfirmDTO) {
        // 1.根据id查询订单
        Orders order = orderMapper.getById(ordersConfirmDTO.getId());

        if (order == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 2.修改订单状态
        order.setStatus(Orders.CONFIRMED);// 3已接单
        orderMapper.update(order);
    }

    /**
     * 各个状态的订单数量统计
     *
     * @return
     */
    public OrderStatisticsVO statistics() {
        // 根据状态，分别查询出待接单、待派送、派送中的订单数量
        Integer toBeConfirmed = orderMapper.countStatus(Orders.TO_BE_CONFIRMED);
        Integer confirmed = orderMapper.countStatus(Orders.CONFIRMED);
        Integer deliveryInProgress = orderMapper.countStatus(Orders.DELIVERY_IN_PROGRESS);

        // 将查询出的数据封装到orderStatisticsVO中响应
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmed);
        orderStatisticsVO.setConfirmed(confirmed);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }


    /**
     * 用户端-催促订单
     * @param id
     */
    public void urgentOrder(Long id) {
        // 1.根据id查询订单
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        //
        Map map = new HashMap<>();
        map.put("type", 2);// 1.来单提醒 2.客户催单
        map.put("orderId", orders.getId());// 订单id
        map.put("content","您的订单"+orders.getNumber()+"催促您尽快配送");// 订单号

        // 参数需要json类型，所以需要进行转化(调用WebSocketServer组件中群发的方法)
        webSocketServer.sendToAllClient(JSON.toJSONString(map));

    }

    /**、
     * 再来一单
     * @param id 订单id
     */
    public void repetiteOrder(Long id) {
        // 查询当前用户id
        Long userId = BaseContext.getCurrentId();

        // 1.根据id查询订单【菜品、套餐】信息
        Orders orders = orderMapper.getById(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        // 根据订单id,查询菜品、套餐信息 select * from order_detail where order_id = ?
        List<OrderDetail> orderDetail = orderDetailMapper.getByOrderId(orders.getId());
        for (OrderDetail detail : orderDetail) {
            ShoppingCart shoppingCart = new ShoppingCart();
            BeanUtils.copyProperties(detail,shoppingCart);

            shoppingCart.setUserId(userId);
            shoppingCart.setCreateTime(LocalDateTime.now());

            // 2. 把【菜品、套餐】插入到购物车
            shoppingCartMapper.insert(shoppingCart);
        }

    }

    /**
     * 用户取消订单
     * @param id
     */
    public void cancelOrder(Long id) throws Exception {
        // ---------【根据id查询oreder，修改订单状态】--------
        Orders orders= orderMapper.getById(id);

        // 1.校验订单是否存在
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);// 订单不存在
        }
        // 2.已接单之后的订单不允许取消 [ 订单状态 1待付款 2待接单 3已接单 4派送中 5已完成 6已取消]
        if (orders.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }

        // 3,订单处于[待接单]状态下取消，需要进行退款
        if (orders.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
          /*
            //调用微信支付退款接口
            weChatPayUtil.refund(
                    orders.getNumber(), //商户订单号
                    orders.getNumber(), //商户退款单号
                    new BigDecimal(0.01),//退款金额，单位 元
                    new BigDecimal(0.01));//原订单金额
           */

            // 3.x [支付状态修改为 退款]
            orders.setPayStatus(Orders.REFUND);// 支付状态，退款
        }

        // 4.修改订单状态为【已取消】
        orders.setStatus(Orders.CANCELLED);// 订单状态，已取消
        orders.setCancelReason("用户取消");// 取消原因，用户自定义
        orders.setCancelTime(LocalDateTime.now());// 取消时间

        orderMapper.update(orders);
        // todo 订单取消之后，购物车中的菜品、套餐数量需要恢复
        // todo oder order——detail删除
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
/*
        // 跳过微信支付
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }


        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
 */

       //------------------------------------------------------------------
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code","ORDERPAID");
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);//
        vo.setPackageStr(jsonObject.getString("package"));//统一下单接口返回的 prepay_id 参数值

        Integer OrderPaidStatus = Orders.PAID;//支付状态，已支付
        Integer OrderStatus = Orders.TO_BE_CONFIRMED;  // 订单状态，待接单
        LocalDateTime check_out_time = LocalDateTime.now();// 付款时间

        Orders orders = orderMapper.getByNumber(ordersPaymentDTO.getOrderNumber());// 订单号
        // update orders set status = ?,pay_status = ? ,checkout_time = ? where id = ?
        orderMapper.updateStatus(OrderStatus, OrderPaidStatus, check_out_time, orders.getId());// 更新订单状态为待接单，支付状态为已支付，付款时间

        //==========================服务器推送消息给前端，提醒商家有新订单============================
        String orderidS = ordersPaymentDTO.getOrderNumber();
        Long orderidL =Long.parseLong(orderidS);//获取订单号

        // 根据订单号查询订单
        Orders ordersDB = orderMapper.getByNumber(orderidS);
        //通过webSocketServer向客户端浏览器推送消息，消息格式json，含3个字段（type、orderId、content）
        Map map = new HashMap();
        map.put("type", 1);//消息类型，1表示来单提醒
        map.put("orderId", ordersDB.getId()); //订单的id
        map.put("content", "订单号：" + orderidL);//订单号

        //转化为json格式
        String json = JSON.toJSONString(map);
        //通过WebSocket实现来单提醒，向客户端浏览器推送消息(调用WebSocketServer类中群发的方法)
        webSocketServer.sendToAllClient(json);
        //==========================推送消息给前端，提醒商家有新订单============================



        return vo;
    }



    /**
     * 2.历史订单分页查询
     * @param ordersPageQueryDTO
     * @return
     */
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        // 设置分页
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        // 分页条件查询Page extent ArrayList [page == orderList]
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList();

        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && page.getTotal() > 0) {// 查询结果不为空，则封装数据
            for (Orders orders : page) {
                Long orderId = orders.getId();// 订单id

                // 根据订单id，查询n条订单【菜品、套餐】明细
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), list);
    }



    /**
     * 1.用户端订单分页查询
     *
     * @param pageNum
     * @param pageSize
     * @param status
     * @return
     */
    public PageResult pageQuery4User(int pageNum, int pageSize, Integer status) {
        // 设置分页
        PageHelper.startPage(pageNum, pageSize);

        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setUserId(BaseContext.getCurrentId());
        ordersPageQueryDTO.setStatus(status);

        // 分页条件查询
        Page<Orders> page = orderMapper.pageQuery(ordersPageQueryDTO);

        List<OrderVO> list = new ArrayList();

        // 查询出订单明细，并封装入OrderVO进行响应
        if (page != null && page.getTotal() > 0) {
            for (Orders orders : page) {
                Long orderId = orders.getId();// 订单id

                // 查询订单明细
                List<OrderDetail> orderDetails = orderDetailMapper.getByOrderId(orderId);

                OrderVO orderVO = new OrderVO();
                BeanUtils.copyProperties(orders, orderVO);
                orderVO.setOrderDetailList(orderDetails);

                list.add(orderVO);
            }
        }
        return new PageResult(page.getTotal(), list);
    }

    /**
     *  查看订单详情查询
     *  id: 订单id
     */
    public OrderVO orderDetail(Long id) {
        // 根据订单id查询订单菜品； select * from order_detail where order_id = ?
        List<OrderDetail> orderDetailList = orderDetailMapper.getByOrderId(id);
        if (orderDetailList != null && orderDetailList.size() > 0) {

            // 根据订单id查询订单信息 select * from orders where id = ?
            Orders order = orderMapper.getById(id);
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);

            orderVO.setOrderDetailList(orderDetailList);// 封装订单明细数据
            return orderVO;
        }
        return null;
    }
}
